/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package net.sourceforge.slcwsn.monitorapp;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.util.Date;
import net.sourceforge.slcwsn.sensors.SensorVisitor;
import net.sourceforge.slcwsn.sensors.SimpleNodeSensorVersion5;
import org.apache.log4j.Logger;

/**
 *
 * @author David Miguel Antunes <davidmiguel [ at ] antunes.net>
 */
public class SensorLongDescriptor implements SensorVisitor {

    private static final String EXCEPTION = "<!DOCTYPE html><html><head></head><body><h1>Exception</h1><br>$EXCEPTION</body></html>";
    private static final String SIMPLE_NODE_SENSOR_VERSION5 = "<!DOCTYPE html><html><head></head><body><h1>Simple Node Sensor Board, version id=5</h1><br><span style=\"font-size: larger;\"><font color=\"#7F7F7F\">Sensor ID:</font> $ID</body></html>";
    private static final Logger logger = Logger.getLogger(EventLongDescriptor.class);
    private String description = "";

    public String getDescription() {
        return description;
    }

    private String color(String text, double val, double yellow, double red) {
        if (val >= red) {
            return "<font color=\"red\">" + text + "</font>";
        } else if (val >= yellow) {
            return "<font color=\"#FFA812\">" + text + "</font>";
        } else {
            return "<font color=\"green\">" + text + "</font>";
        }
    }

    private String getHtml(Object o) {
        try {
            String resource = "net/sourceforge/slcwsn/monitorapp/html/" + o.getClass().getSimpleName() + ".html";
            InputStream is = ClassLoader.getSystemResourceAsStream(resource);
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String html = "";
            String line;
            while ((line = br.readLine()) != null) {
                html += line + System.getProperty("line.separator");
            }
            return html;
        } catch (Exception ex) {
            logger.error(ex);
            return EXCEPTION.replace("$EXCEPTION", ex.getMessage());
        }
    }

    public void visit(SimpleNodeSensorVersion5 sensor) {
        NumberFormat nf = NumberFormat.getNumberInstance();
        nf.setMaximumFractionDigits(3);
        double lost = 100 * ((double) sensor.getLostMessages() / (sensor.getCurrentSeqNum()));
        description = getHtml(sensor).
                replace("$ID", "" + sensor.getId()).
                replace("$N_MESG", "" + sensor.getCurrentSeqNum()).
                replace("$PER_LOST_MESG", "" + color(nf.format(lost), lost, 5, 25)).
                replace("$LAST_IMALIVE", DateFormat.getDateTimeInstance().format(new Date(sensor.getLastIAmAlive()))).
                replace("$LAST_PIR", DateFormat.getDateTimeInstance().format(new Date(sensor.getLastPIRDetection())));
    }
}
